import * as FileApi from '@/api/infra/file'
import { UploadRequestOptions } from 'element-plus/es/components/upload/src/upload'
import axios from 'axios'
import { pathResolve } from '@/utils'

export const getUploadUrl = (): string => {
  return (
    pathResolve(import.meta.env.VITE_API_BASE_URL, import.meta.env.VITE_API_PREFIX) +
    '/infra/file/upload?_platform=web'
  )
}

export const useUpload = (uploadType?: UPLOAD_TYPE) => {
  // 后端上传地址
  const uploadUrl = getUploadUrl()
  // 是否使用前端直连上传
  const clientUpload = (uploadType ?? import.meta.env.VITE_APP_UPLOAD_TYPE) === UPLOAD_TYPE.CLIENT
  // 重写ElUpload上传方法
  const httpRequest = async (options: UploadRequestOptions) => {
    // 模式一：前端上传
    if (clientUpload) {
      // 1. 获取文件预签名地址
      const presignedInfo = await FileApi.getFileUploadPresignedUrl({
        category: options.data?.category as string,
        fileName: options.file.name,
        mimeType: options.file.type,
        size: options.file.size,
        isPrivate: String(options.data?.isPrivate) === 'true'
      })
      // 2. 上传文件
      return axios
        .put(presignedInfo.uploadUrl, options.file, {
          headers: {
            'Content-Type': options.file.type
          }
        })
        .then(() => {
          // 3. 记录文件信息到后端（异步）
          FileApi.createFile({ serialNo: presignedInfo.serialNo })
          // await FileApi.createFile({ serialNo: presignedInfo.serialNo })
          // 通知成功，数据格式保持与后端上传的返回结果一致
          return { path: presignedInfo.path }
        })
    } else {
      // 模式二：后端上传
      // 重写 el-upload httpRequest 文件上传成功会走成功的钩子，失败走失败的钩子
      return new Promise((resolve, reject) => {
        FileApi.uploadFile({
          category: options.data?.category as string,
          file: options.file,
          isPrivate: String(options.data?.isPrivate) === 'true'
        })
          .then((res) => {
            resolve(res)
          })
          .catch((res) => {
            reject(res)
          })
      })
    }
  }

  return {
    uploadUrl,
    httpRequest
  }
}

export enum UPLOAD_TYPE {
  // 直接上传文件服务器
  CLIENT = 'client',
  // 后端服务转发上传
  SERVER = 'server'
}
